<template>
  <a-spin :spinning="confirmLoading">
    <a-form :form="form">
      <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}" v-show="false">
        <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input disabled v-decorator="['id', {rules: [{required: false}]}]" />
        </a-form-item>
      </a-col>

      <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}" v-show="false">
        <a-form-item label="模板ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input disabled v-decorator="['fragmentModelId', {rules: [{required: false}]}]" />
        </a-form-item>
      </a-col>
      <!-- <a-row :gutter="6">
        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}" v-show="false">
          <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input disabled v-decorator="['id', {rules: [{required: true}]}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="片段别名" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input disabled v-decorator="['alias', {rules: [{required: true, min: 2, message: '请输入至少二个字符的规则！'}]}]" />
          </a-form-item>
        </a-col>

        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="片段编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input disabled v-decorator="['code', {rules: [{required: true, message: '请输入'}],initialValue:''}]" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="6">

        <a-col :xl="{span: 11}" :lg="{span: 8}" :md="{span: 12}">
          <a-form-item label="数据条数" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number disabled style="width: 100%;" :min="0" v-decorator="['size', {rules: [{required: true, message: '请输入'}],initialValue:1}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider dashed /> -->

      <a-collapse accordion @change="changeCollapse" v-model="collapseKey" v-show="collapseShow">
        <a-collapse-panel header="数据列表" key="1">
          <a-row :gutter="6">
            <s-table ref="table" size="small" rowKey="id" :columns="columns" :data="loadData">
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tag color="orange" @click="handleEdit(record)"> 编辑 </a-tag>
                  <a-tag color="red" @click="handleDelete(record)" >删除</a-tag>
                </template>
              </span>
            </s-table>
          </a-row>
          <a-divider dashed />
        </a-collapse-panel>
        <a-collapse-panel header="填充数据" key="2" :disabled="false">
          <p style="font-size: 2px;margin-left: 50px;">ps:数据填充需要指定填充的默认站点，需要进行如下操作1-> 创建默认选中站点 2-> 针对当前默认站点进行安装本模板
            后才可进行填充数据到当前默认站点</p>
          <a-divider dashed />
          <a-row :gutter="6">
            <dynamic-forms ref="dynamicForms" :form="form" @submit="submit"></dynamic-forms>
            <div class="table-operator">
              <a-button type="primary" icon="check" @click="handleSubmit">保存</a-button>
              <a-button type="primary" icon="close" @click="handleCancel">取消</a-button>
            </div>
          </a-row>
          <a-divider dashed />
        </a-collapse-panel>
      </a-collapse>
    </a-form>
    <modal-dynamic-form ref="modalDynamicForm" @close="closeModalFrom" @submit="submitModalFrom" title="表单维护"></modal-dynamic-form>
  </a-spin>
</template>

<script>
  import {
    getFragmentFrom,
    insertFragmentAttr,
    pageFragmentAttr,
    delFragmentAttr,
    getDesignAttrById,
    updateFragmentAttr
  } from '@/api/site/fragment.js'
  import moment from 'moment'
  import pick from 'lodash.pick'
  import {
    STable
  } from '@/components'
  import DynamicForms from '@/components/DynamicForms/DynamicForms.vue'
  import ModalDynamicForm from '@/components/DynamicForms/ModalDynamicForm.vue'
  export default {
    components: {
      STable,
      DynamicForms,
      ModalDynamicForm
    },
    data () {
      return {
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 7
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 13
          }
        },
        modalTitle: '',
        modalOpera: 0, // 0：新增 1：编辑
        fields: [],
        collapseKey: null,
        queryParam: {
          dto: {
            fragmentModelId: null
          }
        },
        confirmLoading: false,
        collapseShow: true,
        dataSource: [],
        modelField: [],
        fileItem: null,
        templateId: null,
        form: this.$form.createForm(this),
        // 表头
        columns: [{
            title: '所属站点',
            dataIndex: 'siteName',
            align: 'center',
            width: '140'
          }, {
            title: '标题',
            dataIndex: 'title',
            align: 'center',
            width: '140'
          },
          {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            customRender: text => {
              if (text) return moment(text).format('YYYY-MM-DD')
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: '150px',
            scopedSlots: {
              customRender: 'action'
            }
          }
        ],
        loadData: parameter => {
          if (this.queryParam.dto.fragmentModelId) {
            return pageFragmentAttr(Object.assign(parameter, this.queryParam)).then(
              response => {
                return response.res
              }
            )
          }
        }
      }
    },
    created () {},
    methods: {
      moment,
      init (fileItem, templateId) {
        this.fileItem = fileItem
        this.templateId = templateId
        this.queryParam.dto.fragmentModelId = fileItem.fileInfo.fileName
        this.loadFragmentFrom(fileItem.fileInfo.fileName)
      },
      loadFragmentFrom (fileName) {
        getFragmentFrom({
          fileName: fileName
        }).then(response => {
          const result = response.res
          if (response.code === 0) {
            // this.form.setFieldsValue(pick(result.data, 'id', 'alias', 'code', 'size'))
            this.fields = result.models
          }
        })
      },
      close () {
        this.collapseKey = null
      },
      changeCollapse (key) {
        const that = this
        if (key === '2') {
          setTimeout(function () {
             that.$refs.dynamicForms.setFields(that.fields)
          }, 500)
        } else {
          setTimeout(function () {
            that.handleOk()
          }, 500)
        }
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      handleDelete (record) {
        const that = this
        this.$confirm({
          title: '操作提醒',
          content: '确定要删除吗?',
          onOk () {
            delFragmentAttr({
              id: record.id
            }).then(response => {
              if (response.code === 0) {
                that.handleOk()
                that.$message.info(response.msg)
              } else {
                that.$message.error(response.msg)
              }
            })
          },
          onCancel () {}
        })
      },
      submit (data) {
        data.params = Object.assign({}, data)
        data.fragmentModelId = this.fileItem.fileInfo.fileName
        const json = JSON.stringify(data)
        insertFragmentAttr(json).then(response => {
          if (response.code === 0) {
            this.$message.info('保存成功!')
            this.initFields()
          } else {
            this.$message.error(response.msg)
          }
        })
      },
      handleSubmit () {
        this.$refs.dynamicForms.submitFrom()
      },
      handleCancel () {
        this.$emit('close')
      },
      handleEdit (record) {
         getDesignAttrById({ id: record.id }).then(response => {
           if (response.code === 0) {
              const models = response.res.models
              const data = response.res.data
              this.$refs.modalDynamicForm.initForm(models)
              this.form.setFieldsValue(pick(data, 'id', 'fragmentModelId'))
           }
         })
      },
      submitModalFrom (data) {
        data.params = Object.assign({}, data)
        data.fragmentModelId = this.form.getFieldValue('fragmentModelId')
        data.id = this.form.getFieldValue('id')
        const jsonData = JSON.stringify(data)
        updateFragmentAttr(jsonData).then(response => {
           if (response.code === 0) {
              this.handleOk()
              this.$refs.modalDynamicForm.handleCancel()
           }
           console.log(response)
        })
      },
      closeModalFrom () {
         this.form.setFieldsValue({ id: null })
         this.form.setFieldsValue({ fragmentModelId: null })
      },
      toCollapse (key) {
        this.collapseKey = key
      },
      editSuccess (key) {
        this.toCollapse('1')
        this.handleOk()
      },
      initFields () {
        this.form.resetFields()
        this.$refs.dynamicForms.clearFields()
      }
    }
  }
</script>
